<template>
  <el-affix :offset="0">
    <div class="admin-header">
      <!-- 左边栏收缩、展开 -->
      <div class="header-action-btn" @click="handleMenuWidth">
        <el-icon>
          <Fold v-if="menuStore.menuWidth == '180px'" />
          <Expand v-else />
        </el-icon>
      </div>

      <!-- 右边容器，通过 ml-auto 让其在父容器的右边 -->
      <div class="ml-auto flex">
        <!-- 刷新按钮 -->
        <el-tooltip effect="dark" content="刷新" placement="bottom">
          <div class="header-action-btn" @click="handleRefresh">
            <el-icon>
              <Refresh />
            </el-icon>
          </div>
        </el-tooltip>

        <!-- 跳转前台按钮 -->
        <el-tooltip effect="dark" content="跳转前台" placement="bottom">
          <div class="header-action-btn" @click="router.push('/')">
            <el-icon>
              <Monitor />
            </el-icon>
          </div>
        </el-tooltip>

        <!-- 全屏按钮 -->
        <el-tooltip effect="dark" content="全屏" placement="bottom">
          <div class="header-action-btn" @click="toggle">
            <el-icon>
              <FullScreen v-if="!isFullscreen" />
              <Aim v-else />
            </el-icon>
          </div>
        </el-tooltip>

        <!-- 登录用户头像 -->
        <el-dropdown class="user-dropdown" @command="handleCommand">
          <span class="user-info">
            <!-- 头像 Avatar -->
            <el-avatar
              :size="25"
              class="mr-2"
              src="https://img.quanxiaoha.com/quanxiaoha/f97361c0429d4bb1bc276ab835843065.jpg"
            />
            {{ userStore.userInfo.username }}
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </span>
          <!-- 下拉框 -->
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="updatePassword">修改密码</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- 修改密码 -->
        <!-- :draggable ="true" : 设置对话框可被拖动；
                     :close-on-click-modal="false" ： 设置点击对话框外的位置，对话框不消失；
                     :close-on-press-escape="false" ： 设置按 Esc 键，对话框不消失； -->
        <el-dialog
          v-model="dialogVisible"
          title="修改密码"
          width="40%"
          :draggable="true"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
        >
          <el-form ref="formRef" :rules="rules" :model="form">
            <el-form-item label="用户名" prop="username" label-width="120px">
              <!-- 输入框组件 -->
              <el-input size="large" v-model="form.username" placeholder="请输入用户名" clearable disabled />
            </el-form-item>
            <el-form-item label="密码" prop="password" label-width="120px">
              <el-input
                size="large"
                type="password"
                v-model="form.password"
                placeholder="请输入密码"
                clearable
                show-password
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="rePassword" label-width="120px">
              <el-input
                size="large"
                type="password"
                v-model="form.rePassword"
                placeholder="请确认密码"
                clearable
                show-password
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="onSubmit" v-loading="tableLoading">提交</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </el-affix>
</template>

<style scoped>
  /* 顶栏容器样式 */
  .admin-header {
    margin-left: 10px;
    height: 64px;
    background-color: var(--sidebar-bg-color);
    border-bottom: 1px solid var(--sidebar-border-color);
    box-shadow: var(--header-shadow);
    display: flex;
    align-items: center;
    padding-right: 16px;
    transition: all 0.6s cubic-bezier(0.16, 1, 0.3, 1);
  }

  /* 头部操作按钮通用样式 */
  .header-action-btn {
    width: 42px;
    height: 36px;
    margin: 14px 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--sidebar-text-color);
    cursor: pointer;
    transition: all 0.3s ease;
    border-radius: 18px;
    background-color: var(--sidebar-bg-color);
    border: 2px solid #dee2fd;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }

  .header-action-btn:hover {
    background-color: var(--sidebar-hover-bg-color);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    transform: translateY(-1px);
  }

  /* 用户信息下拉样式 */
  .user-dropdown {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 8px;
  }

  .user-info {
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--sidebar-text-color);
    font-size: 14px;
    cursor: pointer;
    padding: 0 12px;
    height: 36px;
    margin: 14px 4px;
    transition: all 0.3s ease;
    border-radius: 18px;
    background-color: var(--sidebar-bg-color);
    border: 1px solid var(--sidebar-border-color);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }

  .user-info:hover {
    background-color: var(--sidebar-hover-bg-color);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    transform: translateY(-1px);
  }

  .user-info .el-avatar {
    margin-right: 8px;
    --el-avatar-bg-color: var(--primary-color);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  /* 修改密码对话框样式调整 */
  :deep(.el-dialog__header) {
    background-color: var(--sidebar-bg-color);
    border-bottom: 1px solid var(--sidebar-border-color);
  }

  :deep(.el-dialog__title) {
    color: var(--sidebar-text-color);
  }

  /* CSS 变量定义 */
  :root {
    --header-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    --sidebar-bg-color: #ffffff;
    --sidebar-text-color: #606266;
    --sidebar-hover-bg-color: #f5f7fa;
    --sidebar-border-color: #ebeef5;
    --primary-color: #409eff;
  }
</style>

<script setup>
  // 引入必要的模块和工具
  import { useMenuStore } from "@/stores/menu";
  import { useFullscreen } from "@vueuse/core";
  import { useUserStore } from "@/stores/user";
  import { showMessage, showModel } from "@/composables/util";
  import { useRouter } from "vue-router";
  import { updateAdminPassword } from "@/api/admin/user";
  import { ref, reactive, watch } from "vue";

  // 状态管理和路由
  const menuStore = useMenuStore();
  const userStore = useUserStore();
  const router = useRouter();

  // 全屏功能
  const { isFullscreen, toggle } = useFullscreen();

  // 表单相关状态
  const dialogVisible = ref(false);
  const formRef = ref(null);
  const tableLoading = ref(false);

  // 表单数据和验证规则
  const form = reactive({
    username: userStore.userInfo.username || "",
    password: "",
    rePassword: ""
  });

  const rules = {
    username: [
      {
        required: true,
        message: "用户名不能为空",
        trigger: "blur"
      }
    ],
    password: [
      {
        required: true,
        message: "密码不能为空",
        trigger: "blur"
      }
    ],
    rePassword: [
      {
        required: true,
        message: "确认密码不能为空",
        trigger: "blur"
      }
    ]
  };

  // 处理菜单宽度变化
  const handleMenuWidth = () => {
    menuStore.handleMenuWidth();
  };

  // 刷新页面
  const handleRefresh = () => location.reload();

  // 处理下拉菜单命令
  const handleCommand = command => {
    if (command === "updatePassword") {
      dialogVisible.value = true;
    } else if (command === "logout") {
      logout();
    }
  };

  // 退出登录
  const logout = () => {
    showModel("是否确认要退出登录？").then(() => {
      userStore.logout();
      showMessage("退出登录成功！");
      router.push("/login");
    });
  };

  // 提交表单
  const onSubmit = () => {
    tableLoading.value = true;
    formRef.value.validate(valid => {
      if (!valid) {
        tableLoading.value = false;
        return false;
      }

      if (form.password !== form.rePassword) {
        showMessage("两次密码输入不一致，请检查！", "warning");
        tableLoading.value = false;
        return;
      }

      updateAdminPassword(form).then(res => {
        tableLoading.value = false;
        if (res.success === true) {
          showMessage("密码重置成功，请重新登录！");
          userStore.logout();
          dialogVisible.value = false;
          router.push("/login");
        } else {
          showMessage(res.message, "error");
        }
      });
    });
  };

  // 监听用户名变化
  watch(
    () => userStore.userInfo.username,
    newValue => {
      form.username = newValue;
    }
  );
</script>
